package com.gsafety.wellsfort.service.security.impl;

import com.gsafety.wellsfort.common.context.LoginContextUtil;
import com.gsafety.wellsfort.common.enums.PrivilegeEnum;
import com.gsafety.wellsfort.common.enums.RoleGroupEnum;
import com.gsafety.wellsfort.common.enums.StatusEnum;
import com.gsafety.wellsfort.common.util.ApiResponse;
import com.gsafety.wellsfort.common.util.MapUtils;
import com.gsafety.wellsfort.common.util.ResultCode;
import com.gsafety.wellsfort.dao.knowledge.CoursewarePrivilegeDAO;
import com.gsafety.wellsfort.dao.knowledge.MaterialPrivilegeDAO;
import com.gsafety.wellsfort.dao.knowledge.TeachaidPrivilegeDAO;
import com.gsafety.wellsfort.dao.security.AdminRoleRelDAO;
import com.gsafety.wellsfort.dao.security.MenuDAO;
import com.gsafety.wellsfort.dao.security.MenuRoleRelDAO;
import com.gsafety.wellsfort.dao.security.RoleDAO;
import com.gsafety.wellsfort.domain.PageQuery;
import com.gsafety.wellsfort.domain.bo.UserBO;
import com.gsafety.wellsfort.domain.dto.ids.KnowledgeQueryDto;
import com.gsafety.wellsfort.domain.form.RoleForm;
import com.gsafety.wellsfort.domain.form.Tree;
import com.gsafety.wellsfort.domain.model.knowledge.CoursewarePrivilege;
import com.gsafety.wellsfort.domain.model.knowledge.MaterialPrivilege;
import com.gsafety.wellsfort.domain.model.knowledge.TeachaidPrivilege;
import com.gsafety.wellsfort.domain.model.security.*;
import com.gsafety.wellsfort.domain.vo.KnowledgeResultVO;
import com.gsafety.wellsfort.domain.vo.MenuResultVO;
import com.gsafety.wellsfort.domain.vo.QueryVO;
import com.gsafety.wellsfort.domain.vo.security.RoleVO;
import com.gsafety.wellsfort.service.security.IRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleDAO roleDAO;
    @Autowired
    private MenuRoleRelDAO menuRoleRelDAO;

    @Autowired
    private MenuDAO menuDAO;

    @Autowired
    private AdminRoleRelDAO adminRoleRelDAO;

    /**
     * 教材
     */
    @Autowired
    private CoursewarePrivilegeDAO coursewarePrivilegeDAO;

    /**
     * 课件
     */
    @Autowired
    private MaterialPrivilegeDAO materialPrivilegeDAO;

    /**
     * 教具
     */
    @Autowired
    private TeachaidPrivilegeDAO teachaidPrivilegeDAO;

    @Override
    public boolean addRole(RoleVO roleVO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleVO, role);
        Date date = new Date();
        role.setCreated(date);
        role.setModified(date);
        role.setCreator(LoginContextUtil.getUserName());
        role.setOperator(LoginContextUtil.getUserName());
        if (role.getStatus() == null) {
            role.setStatus(StatusEnum.ENABLE.getValue().byteValue());
        }
        return roleDAO.insertSelective(role) > 0 ? true : false;
    }

    @Override
    public boolean updateRole(RoleVO roleVO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleVO, role);
        Date date = new Date();
        role.setModified(date);
        role.setOperator(LoginContextUtil.getUserName());
        if (role.getStatus() == null) {
            role.setStatus(StatusEnum.ENABLE.getValue().byteValue());
        }
        return roleDAO.updateByPrimaryKeySelective(role) > 0 ? true : false;
    }

    @Override
    public boolean setPermission(RoleForm roleForm) {
        //先删除该角色关联菜单
        if (roleForm != null && roleForm.getRoleId() != null) {
            MenuRoleRel menuRoleRel = null;
            Date date = new Date();
            menuRoleRelDAO.deleteByRoleId(roleForm.getRoleId());
            if (roleForm.getMenuIds() != null) {
                List<Integer> menuIds = roleForm.getMenuIds();
                for (Integer menuId : menuIds) {
                    //重新绑定映射关系
                    menuRoleRel = MenuRoleRel.builder().roleId(roleForm.getRoleId()).menuId(menuId).
                            status(StatusEnum.ENABLE.getValue().byteValue()).
                            creator(LoginContextUtil.getUserName()).operator(LoginContextUtil.getUserName()).
                            created(date).modified(date).
                            build();
                    menuRoleRelDAO.insertSelective(menuRoleRel);
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public ApiResponse<List<Role>> pageQuery(QueryVO query) {
        UserBO userBO = LoginContextUtil.getUserBo();
        Map<String, Object> param = MapUtils.buildQueryParam(query);
        List<Integer> roleGroupList = new ArrayList<>();
        //查询维度设置
        if (RoleGroupEnum.SCHOOL_ADMIN.getCode().equals(userBO.getType())) {
            //学校后台管理员查询学校后台以及学校教师管理员
            roleGroupList.add(RoleGroupEnum.SCHOOL_ADMIN.getCode());
            roleGroupList.add(RoleGroupEnum.TEACHER_ADMIN.getCode());
            param.put("roleGroupList", roleGroupList);
        } else if (RoleGroupEnum.TEACHER_ADMIN.getCode().equals(userBO.getType())) {
            //学校教师管理员查看学校教师管理员
            roleGroupList.add(RoleGroupEnum.TEACHER_ADMIN.getCode());
            param.put("roleGroupList", roleGroupList);
        }
        Integer count = roleDAO.countRole(param);
        List<Role> list = roleDAO.pageQuery(param);
        return ApiResponse.success(list, count);
    }

    @Override
    public ApiResponse<List<Tree>> getPermission(Integer roleId) {
        List<Tree> treeList = new ArrayList<>();
        List<Menu> list = menuDAO.queryByRoleId(roleId);
        Map<String, Tree> cache = new HashMap<>(8);
        Tree leaf = null;
        int codeLength = 3;
        if (list != null && list.size() > 0) {
            for (Menu menu : list) {
                leaf = new Tree(menu.getId(), menu.getName(), menu.getType().intValue(), menu.getIcon(), menu.getViewLevelCode(), menu.getCheck());
                String code = menu.getViewLevelCode();
                Tree parent = null;
                if (code != null && code.length() > codeLength) {
                    parent = cache.get(StringUtils.substring(code, 0, code.length() - 3));
                }
                if (parent != null) {
                    parent.addChildren(leaf);
                } else {
                    treeList.add(leaf);
                }
                cache.put(menu.getViewLevelCode(), leaf);
            }
        }
        return ApiResponse.success(treeList);
    }

    @Override
    public ApiResponse checkPermission(String opCode) {
        Admin admin = LoginContextUtil.getAdmin();
        if (admin == null) {
            return ApiResponse.error(ResultCode.INVALID_PARAM);
        }
        Integer roleId = null;
        List<MenuRoleRel> menuRoleRelList = null;
        Menu menu;
        List<AdminRoleRel> list = adminRoleRelDAO.selectByAdminId(admin.getId());
        if (list != null && list.size() > 0) {
            for (AdminRoleRel roleRel : list) {
                roleId = roleRel.getRoleId();
                menuRoleRelList = menuRoleRelDAO.selectByRoleId(roleId);
                if (menuRoleRelList != null && menuRoleRelList.size() > 0) {
                    for (MenuRoleRel menuRoleRel : menuRoleRelList) {
                        menu = menuDAO.selectByPrimaryKey(menuRoleRel.getMenuId());
                        if (menu != null && menu.getOpCode().equalsIgnoreCase(opCode)) {
                            return ApiResponse.success();
                        }
                    }
                }
            }
        }
        return ApiResponse.error(ResultCode.ERROR, "没有操作权限");
    }

    @Override
    public Role get(Integer rolId) {
        return roleDAO.selectByPrimaryKey(rolId);
    }

    @Override
    public ApiResponse<List<KnowledgeResultVO>> getKnowledgePermission(KnowledgeQueryDto knowledgeQueryDto) {
        List<KnowledgeResultVO> resultList = new ArrayList<>();
        Admin admin = LoginContextUtil.getAdmin();
        if (admin == null) {
            return ApiResponse.error(ResultCode.NOT_AUTHORIZED);
        }
        if (knowledgeQueryDto.getType() == null) {
            return ApiResponse.error(ResultCode.INVALID_PARAM);
        }
        List<Role> roleList = roleDAO.getAllRole();
        for (Role role : roleList) {
            KnowledgeResultVO knowledgeResultVO = new KnowledgeResultVO();
            knowledgeResultVO.setRoleId(role.getId());
            knowledgeResultVO.setRoleName(role.getName());
            resultList.add(knowledgeResultVO);
        }
        if (knowledgeQueryDto.getType() == 2) {
            for (KnowledgeResultVO knowledgeResultVO : resultList) {
                MenuResultVO resultVO1 = MenuResultVO.builder().menuId(PrivilegeEnum.COURSE_WARE_READ.getMenuId()).menuName("阅读").selected(false).build();
                MenuResultVO resultVO2 = MenuResultVO.builder().menuId(PrivilegeEnum.COURSE_WARE_DOWNLOAD.getMenuId()).menuName("下载").selected(false).build();
                knowledgeResultVO.addMenu(resultVO1);
                knowledgeResultVO.addMenu(resultVO2);
            }
            if (knowledgeQueryDto.getId() != null) {
                List<CoursewarePrivilege> coursewarePrivilegeList = coursewarePrivilegeDAO.selectByCoursewareId(knowledgeQueryDto.getId());
                if (coursewarePrivilegeList != null && coursewarePrivilegeList.size() > 0) {
                    for (CoursewarePrivilege coursewarePrivilege : coursewarePrivilegeList) {
                        for (KnowledgeResultVO knowledgeResultVO : resultList) {
                            if (coursewarePrivilege.getRoleId().equals(knowledgeResultVO.getRoleId())) {
                                knowledgeResultVO.setMenuSelect(coursewarePrivilege.getMenuId());
                            }
                        }
                    }
                }
            }
        } else if (knowledgeQueryDto.getType() == 1) {
            for (KnowledgeResultVO knowledgeResultVO : resultList) {
                MenuResultVO resultVO1 = MenuResultVO.builder().menuId(PrivilegeEnum.MATERIAL_READ.getMenuId()).menuName("阅读").selected(false).build();
                MenuResultVO resultVO2 = MenuResultVO.builder().menuId(PrivilegeEnum.MATERIAL_DOWNLOAD.getMenuId()).menuName("下载").selected(false).build();
                knowledgeResultVO.addMenu(resultVO1);
                knowledgeResultVO.addMenu(resultVO2);
            }
            if (knowledgeQueryDto.getId() != null) {
                List<MaterialPrivilege> materialPrivilegeList = materialPrivilegeDAO.selectByMaterialId(knowledgeQueryDto.getId());
                if (materialPrivilegeList != null && materialPrivilegeList.size() > 0) {
                    for (MaterialPrivilege materialPrivilege : materialPrivilegeList) {
                        for (KnowledgeResultVO knowledgeResultVO : resultList) {
                            if (materialPrivilege.getRoleId().equals(knowledgeResultVO.getRoleId())) {
                                knowledgeResultVO.setMenuSelect(materialPrivilege.getMenuId());
                            }
                        }
                    }
                }
            }
        } else if (knowledgeQueryDto.getType() == 3) {
            //教具使用权限,控制的为课程中该操作者是否有添加该教具的权限
            for (KnowledgeResultVO knowledgeResultVO : resultList) {
                MenuResultVO resultVO1 = MenuResultVO.builder().menuId(PrivilegeEnum.TEACHING_AID_USE.getMenuId()).menuName("使用").selected(false).build();
                knowledgeResultVO.addMenu(resultVO1);
            }
            if (knowledgeQueryDto.getId() != null) {
                List<TeachaidPrivilege> teachaidPrivilegeList = teachaidPrivilegeDAO.selectByTeachaidId(knowledgeQueryDto.getId());
                if (teachaidPrivilegeList != null && teachaidPrivilegeList.size() > 0) {
                    for (TeachaidPrivilege teachaidPrivilege : teachaidPrivilegeList) {
                        for (KnowledgeResultVO knowledgeResultVO : resultList) {
                            if (teachaidPrivilege.getRoleId().equals(knowledgeResultVO.getRoleId())) {
                                knowledgeResultVO.setMenuSelect(teachaidPrivilege.getMenuId());
                            }
                        }
                    }
                }
            }
        }
        return ApiResponse.success(resultList);
    }

    @Override
    public ApiResponse<List<Role>> getAllByGroup(Integer schoolId) {
        List<Integer> roleGroupList = new ArrayList<>();
        //查询维度设置
        Map<String, Object> param = new HashMap<>(8);
        param.put(PageQuery.KEY_START_INDEX, 0);
        param.put(PageQuery.KEY_PAGE_SIZE, 9999);
        param.put("status", 1);
        if (schoolId != null && schoolId != 1) {
            //学校后台管理员查询学校后台以及学校教师管理员
            roleGroupList.add(RoleGroupEnum.SCHOOL_ADMIN.getCode());
            roleGroupList.add(RoleGroupEnum.TEACHER_ADMIN.getCode());
            param.put("roleGroupList", roleGroupList);
        }
        Integer count = roleDAO.countRole(param);
        List<Role> list = roleDAO.pageQuery(param);
        return ApiResponse.success(list, count);
    }
}
